package com.yimicloud.common.freemarker;

import java.io.File;

/**
 * Created by Justin on 2015/9/7.
 */
public class FileUtil {
    public FileUtil() {
    }

    public static boolean delete(String fileName) {
        File file = new File(fileName);
        return delete(file);
    }

    public static boolean delete(File file) {
        return !file.exists()?true:(file.isFile()?file.delete():deleteDir(file));
    }

    public static boolean deleteDir(File dirFile) {
        boolean flag = true;
        if(dirFile == null) {
            return flag;
        } else {
            File[] files = dirFile.listFiles();
            File[] var6 = files;
            int var5 = files.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                File file = var6[var4];
                if(file.isFile()) {
                    flag = file.delete();
                } else {
                    flag = deleteDir(file);
                }

                if(!flag) {
                    return false;
                }
            }

            return true;
        }
    }

    public static File getClearDirectory(String directroyPath) {
        File dirFile = new File(directroyPath);
        return getClearDirectory(dirFile);
    }

    private static File getClearDirectory(File dirFile) {
        if(!dirFile.exists()) {
            dirFile.mkdirs();
            return dirFile;
        } else {
            String[] list = dirFile.list();
            if(list != null && list.length > 0) {
                boolean delete = delete(dirFile);
                if(!delete) {
                    return null;
                }
            }

            return dirFile;
        }
    }

    public static void deleteFile(File file) {
        if(file.exists()) {
            if(file.isFile()) {
                file.delete();
            } else if(file.isDirectory()) {
                File[] files = file.listFiles();

                for(int i = 0; i < files.length; ++i) {
                    deleteFile(files[i]);
                }
            }

            file.delete();
        } else {
            System.out.println("所删除的文件不存在！\n");
        }

    }
}

